package com.foreverwin.jzymes.common.service.impl;

import com.foreverwin.jzymes.common.mapper.ActivityRuleAdviceMapper;
import com.foreverwin.jzymes.common.service.IActivityRuleAdviceService;
import com.foreverwin.jzymes.common.util.BOHandleUtil;
import com.foreverwin.jzymes.framework.util.I18nUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ActivityRuleAdviceServiceImpl implements IActivityRuleAdviceService {

    @Autowired
    ActivityRuleAdviceMapper activityRuleAdviceMapper;

    /**
     * 查询作业规则
     *
     * @param activityId
     * @return
     */
    public Map<String,String> findActivityRules( String activityId ){
        Assert.hasText( activityId, I18nUtil.getI18nText("common.ActivityNotBlank" ) );
        String activityBo = BOHandleUtil.buildActivityHandle( activityId );
        List<Map<String,String>> activityRules = activityRuleAdviceMapper.selectAcivityRules( activityBo );
        Map<String,String> ruleMap = new HashMap<>();
        for( Map<String,String> map : activityRules ){
            ruleMap.put( map.get( "EXEC_UNIT_OPTION" ), map.get( "SETTING" ) );
        }
        return ruleMap;
    }

    /**
     * 查询作业规则
     *
     * @param activityId
     * @param ruleName
     * @return
     */
    public String findActivityRule( String activityId, String ruleName ){
        Map<String,String> ruleMap = findActivityRules( activityId );
        if( ruleMap.containsKey( ruleName ) ){
            return ruleMap.get( ruleName );
        }
        return "";
    }

    /**
     * 修改作业规则
     *
     * @param activityId
     * @param ruleList
     */
    @Transactional( propagation = Propagation.REQUIRED, rollbackFor = Exception.class )
    public void updateActivityRule( String activityId, List<Map<String,Object>> ruleList ){
        for( Map<String,Object> ruleMap : ruleList ){
            updateActivityRule( activityId, (String) ruleMap.get( "ruleName" ), (String) ruleMap.get( "value" ) );
        }
    }

    /**
     * 修改作业规则
     *
     * @param activityId
     * @param ruleName
     * @param value
     * @return
     */
    @Transactional( propagation = Propagation.REQUIRED, rollbackFor = Exception.class )
    public int updateActivityRule( String activityId, String ruleName, String value ){
        Assert.hasText( activityId, I18nUtil.getI18nText("common.ActivityNotBlank" ) );
        String activityBo = BOHandleUtil.buildActivityHandle( activityId );
        return activityRuleAdviceMapper.updateActivityRule( activityBo, ruleName, value );
    }

}
